package org.androidpn.server.xmpp.push;

import org.androidpn.server.entity.Role;
import org.androidpn.server.entity.Room;
import org.androidpn.server.entity.RoomMessage;
import org.androidpn.server.entity.User;
import org.androidpn.server.xmpp.packet.RoomMessagePacket;
import org.androidpn.server.xmpp.packet.RoomMessagePacket.Operation;
import org.androidpn.server.xmpp.session.ClientSession;
import org.androidpn.server.xmpp.session.SessionManager;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.jivesoftware.smack.util.StringUtils;
import org.xmpp.packet.IQ;

/**
 * 推送游戏房间信息线程
 * 
 * @author 蔡琪
 * 
 */
public class PushRoomMessageToClientThread implements Runnable {

	protected final Log log = LogFactory.getLog(getClass());

	private RoomMessage roomMessage;
	private SessionManager sessionManager;

	public PushRoomMessageToClientThread(RoomMessage roomMessage,
			SessionManager sessionManager) {
		this.roomMessage = roomMessage;
		this.sessionManager = sessionManager;
	}

	public void run() {
		Room room = roomMessage.getRoom();
		// roomMessage.setRoom(null);
		if (room != null) {
			for (Role role : room.getRoles()) {
				User user = role.getUser();
				ClientSession session = sessionManager.getSession(user
						.getUsername().toLowerCase());
				if (session != null) {
					RoomMessagePacket roomMessagePacket = new RoomMessagePacket();
					roomMessagePacket.setRoomMessage(roomMessage);
					roomMessagePacket.setOperation(Operation.pushMessage);
					IQ iq = new IQ();
					iq.setID("PushRoomMessageToClientThread");
					iq.setTo(session.getAddress());
					if (roomMessagePacket.getChildElementXML() != null) {
						Document doc;
						try {
							doc = DocumentHelper.parseText(roomMessagePacket
									.getChildElementXML());
							Element element = doc.getRootElement();
							iq.setChildElement(element.createCopy());
							iq.setType(IQ.Type.result);
							log.debug("send "
									+ StringUtils.unescapeNode(iq.toXML()));
							session.process(iq);
						} catch (DocumentException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
}